<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input v-model="listQuery.shopName" clearable class="filter-item" style="width: 200px;" placeholder="请输入店铺名称" />
      <el-input v-model="listQuery.name" clearable class="filter-item" style="width: 200px;" placeholder="请输入联系人" />
      <el-button v-permission="['GET /admin/shop/list']" class="filter-item" type="primary" icon="el-icon-search"
        @click="handleFilter">查找</el-button>
      <el-button v-permission="['POST /admin/shop/create']" class="filter-item" type="primary" icon="el-icon-edit"
        @click="handleCreate">添加</el-button>
      <el-button :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">导出</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row>

      <el-table-column align="center" width="60px" label="ID" prop="id" sortable />

      <el-table-column align="center" label="店铺图片" prop="shopUrl">
        <template slot-scope="scope">
          <img v-if="scope.row.shopUrl" :src="scope.row.shopUrl" width="80">
        </template>
      </el-table-column>

      <el-table-column align="center" label="店铺名称" prop="shopName" />

      <el-table-column align="center" label="店铺地址" prop="shopAddress" />



      <el-table-column align="center" label="联系人" prop="name" />

      <el-table-column align="center" label="联系人号码" prop="shopPhone" />

      <el-table-column align="center" width="200" label="店铺开关" prop="shopOff">
        <template slot-scope="scope">
          <el-switch @change="handleChange(scope.row)"
            v-model="scope.row.shopOff==1?false:true"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-text="营业"
            inactive-text="歇业">
          </el-switch>
        </template>
      </el-table-column>

      <el-table-column align="center" label="地理位置" width="300" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button round size="default">{{scope.row.longitude}}</el-button>
          <span> - </span>
          <el-button round size="default">{{scope.row.latitude}}</el-button>
        </template>
      </el-table-column>

      <el-table-column align="center" label="商家小程序码" prop="shareUrl">
        <template slot-scope="scope">
          <img v-if="scope.row.shareUrl" :src="scope.row.shareUrl" width="80">
        </template>
      </el-table-column>

      <el-table-column align="center" label="绑定管理" width="150">
        <template slot-scope="scope">
          <el-button v-if="scope.row.adminId==0" type="danger" size="mini" icon="el-icon-edit" @click="handleUpdate2(scope.row)">未绑定</el-button>
          <el-button v-if="scope.row.adminId>0" disabled type="primary" size="mini" icon="el-icon-check">已绑定</el-button>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" width="300" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-permission="['POST /admin/shop/update']" v-if="scope.row.adminId > 0" type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button v-permission="['POST /admin/shop/update']" v-if="scope.row.adminId > 0" type="success" plain size="mini" @click="handleCreateSetting(scope.row)">设置</el-button>
          <el-button v-permission="['POST /admin/shop/delete']" type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />


    <!-- 添加或修改对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="dataForm" status-icon label-position="left" label-width="100px"
        style="width: 400px; margin-left:50px;">
        <el-form-item label="店铺名称" prop="shopName">
          <el-input v-model="dataForm.shopName" />
        </el-form-item>
        <el-form-item label="店铺地址" prop="shopAddress">
          <el-input v-model="dataForm.shopAddress" />
        </el-form-item>
        <!--
        <el-form-item label="校园负责人" prop="adminId" >
          <el-select v-model="dataForm.adminId" clearable>
            <el-option v-for="item in listAdmin" :key="item.username" :label="item.username" :value="item.id" />
          </el-select>
        </el-form-item>-->
        <el-form-item label="联系人" prop="name">
          <el-input v-model="dataForm.name" />
        </el-form-item>
        <el-form-item label="联系人号码" prop="shopPhone">
          <el-input v-model="dataForm.shopPhone" />
        </el-form-item>
        <el-form-item label="地理坐标" prop="longitude">
          <el-col :span="11">
            <el-input v-model="dataForm.longitude" placeholder="经度" />
          </el-col>
          <el-col :span="2" style="text-align: center;">-</el-col>
          <el-col :span="11">
            <el-input v-model="dataForm.latitude" placeholder="纬度" />
          </el-col>
        </el-form-item>

        <el-form-item label="店面标签" prop="label">
          <el-input v-model="dataForm.label" placeholder="如: 新店开业"/>
        </el-form-item>

        <el-form-item label="门店图片" prop="shopUrl">
          <el-upload :headers="headers" :action="uploadPath" :show-file-list="false" :on-success="uploadUrl"
            :before-upload="checkFileSize" class="avatar-uploader" accept=".jpg,.jpeg,.png,.gif">
            <img v-if="dataForm.shopUrl" :src="dataForm.shopUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过1024kb</div>
          </el-upload>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确定</el-button>
        <el-button v-else type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>

    <!-- 绑定APP用户对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormBound">
      <el-form ref="dataForm" :rules="rules" :model="dataForm" status-icon label-position="left" label-width="100px"
        style="width: 400px; margin-left:50px;">
        <el-form-item label="APP用户ID" prop="name">
          <el-input v-model="dataForm.adminId" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormBound = false">取消</el-button>
        <el-button type="primary" @click="updateBoundData">确定</el-button>
      </div>
    </el-dialog>

    <!-- 店铺设置对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormSetting">
      <el-form ref="dataFormSetting" :rules="setting_rules" :model="dataFormSetting" status-icon label-position="left" label-width="100px"
        style="width: 400px; margin-left:50px;">
        <el-form-item label="店铺ID" prop="shopId">
          <el-input v-model="dataFormSetting.shopId" disabled/>
        </el-form-item>
        <el-form-item label="店长名字" prop="name">
          <el-input v-model="dataFormSetting.name"placeholder="请输入店长真实名字" />
        </el-form-item>
        <el-form-item label="店铺号码" prop="shopPhone">
          <el-input v-model="dataFormSetting.shopPhone" placeholder="请输入店主手机号码"/>
        </el-form-item>
        <el-form-item label="店铺费率" prop="rate">
          <el-input v-model="dataFormSetting.rate" placeholder="请输入平台收取的费率"/>
        </el-form-item>
        <el-form-item label="店铺配送费" prop="deliveryPrice">
          <el-input v-model="dataFormSetting.deliveryPrice" placeholder="请输入店铺配送订单费用" />
        </el-form-item>
        <el-form-item label="店铺起送价" prop="initialPrice">
          <el-input v-model="dataFormSetting.initialPrice" placeholder="请输入店铺订单起送价格" />
        </el-form-item>
        <el-form-item label="配送选择" prop="deliveryStatus">
          <template>
            <el-radio v-model="elRadioStatus" label="1" @change="UpdateDeliveryStatus('1')" >平台配送</el-radio>
            <el-radio v-model="elRadioStatus" label="0" @change="UpdateDeliveryStatus('0')" >商家配送</el-radio>
          </template>
        </el-form-item>
        <el-form-item label="营业时间" prop="deliveryStart">
          <!--
          <el-col :span="11">
            <el-input v-model="dataFormSetting.deliveryStart" placeholder="开始时间" />
          </el-col>
          <el-col :span="2" style="text-align: center;">-</el-col>
          <el-col :span="11">
            <el-input v-model="dataFormSetting.deliveryEnd" placeholder="结束时间" />
          </el-col>-->
        <el-time-select style="width: 130px;"
          placeholder="开始时间"
          v-model="dataFormSetting.deliveryStart"
          :picker-options="{
            start: '00:00',
            step: '00:30',
            end: '23:30'
          }">
        </el-time-select>
        --
        <el-time-select style="width: 130px;"
          placeholder="结束时间"
          v-model="dataFormSetting.deliveryEnd"
          :picker-options="{
            start: '00:30',
            step: '00:30',
            end: '23:30',
            minTime: dataFormSetting.deliveryStart
          }">
        </el-time-select>


        </el-form-item>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormSetting = false">取消</el-button>
        <el-button v-if="dialogStatus=='setting'" type="primary" @click="createShopSettingData">确定</el-button>
        <el-button v-else type="primary" @click="updateShopSettingData">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>



<script>
  import {
    listShop,
    createShop,
    updateShop,
    deleteShop,
    listAdmin,
    updateShopOff,
    createShopSetting,
    updateShopSetting,
    getOneSetting,
    updateShopBound
  } from '@/api/shop'
  import {
    uploadPath
  } from '@/api/storage'
  import {
    getToken
  } from '@/utils/auth'
  import Pagination from '@/components/Pagination' // Secondary package based on el-pagination

  export default {
    name: 'Ad',
    components: {
      Pagination
    },
    data() {
      return {
        uploadPath,
        list: [],
        total: 0,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 20,
          name: undefined,
          shopName: undefined,
          shopPhone: undefined
        },
        dataForm: {
          id: undefined,
          name: undefined,
          label: undefined,
          adminId: undefined,
          shopName: undefined,
          shopAddress: undefined,
          shopPhone: undefined,
          latitude: undefined,
          longitude: undefined,
          shopUrl: undefined,
          shopOff: undefined
        },
        dataFormSetting: {
          id: undefined,
          shopId: undefined,
          shopPhone: undefined,
          shopNotice: undefined,
          rate: undefined,
          deliveryPrice: undefined,
          initialPrice: undefined,
          deliveryStatus: 1,
          deliveryStart: undefined,
          deliveryEnd: undefined,
          unionId: undefined,
          gzhOpenId: undefined,
          mpOpenId: undefined
        },
        dialogFormVisible: false,
        dialogFormSetting: false,
        dialogFormBound: false,
        dialogStatus: '',
        textMap: {
          update: '编辑',
          create: '创建',
          setting: '设置',
          updateSetting: '编辑设置'
        },
        rules: {
          name: [{required: true,message: '联系人不能为空',trigger: 'blur'}],
          shopName: [{required: true,message: '门店名称不能为空',trigger: 'blur'}],
          shopAddress: [{required: true,message: '门店地址不能为空',trigger: 'blur'}],
          shopPhone: [{required: true,message: '联系人号码不能为空',trigger: 'blur'}],
          shopUrl: [{required: true,message: '门店图片不能为空',trigger: 'blur'}],
          adminId: [{required: true,message: '负责人不能为空',trigger: 'blur'}],
          longitude: [{required: true,message: '经纬度不能为空',trigger: 'blur'}],
        },
        setting_rules: {
          name: [{required: true,message: '店铺店长名字不能为空',trigger: 'blur'}],
          shopId: [{required: true,message: '店铺id不能为空',trigger: 'blur'}],
          shopPhone: [{required: true,message: '店铺号码不能为空',trigger: 'blur'}],
          rate: [{required: true,message: '店铺费率不能为空',trigger: 'blur'}],
          deliveryPrice: [{required: true,message: '店铺配送费不能为空',trigger: 'blur'}],
          initialPrice: [{required: true,message: '店铺起送价不能为空',trigger: 'blur'}],
          deliveryStart: [{required: true,message: '店铺配送时间不能为空',trigger: 'blur'}],
          deliveryEnd: [{required: true,message: '店铺配送时间不能为空',trigger: 'blur'}],
          deliveryStatus: [{required: true,message: '请选择配送选项',trigger: 'blur'}],
        },
        downloadLoading: false,
        listAdmin: {},
        elRadioStatus: '1'

      }
    },
    computed: {
      headers() {
        return {
          'X-Litemall-Admin-Token': getToken()
        }
      }
    },
    created() {
      this.getList()
    },
    methods: {
      getList() {
        this.listLoading = true
        listShop(this.listQuery)
          .then(response => {
            this.list = response.data.data.list
            this.total = response.data.data.total
            this.listLoading = false
          })
          .catch(() => {
            this.list = []
            this.total = 0
            this.listLoading = false
          })
      },
      UpdateDeliveryStatus(index){
        if(index == '1'){
          this.dataFormSetting.deliveryStatus = 1
        }else{
          this.dataFormSetting.deliveryStatus = 0
        }
        this.elRadioStatus = index;
      },
      handleChange(row) {
        //console.log(value, direction, movedKeys);
        var off = 0;
        if(row.shopOff == 0){
            off = 1;
        }
        this.dataForm = row
        this.dataForm.shopOff = off
        this.updateShopOff()
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      resetForm() {
        this.dataForm = {
          id: undefined,
          name: undefined,
          shopName: undefined,
          shopAddress: undefined,
          shopPhone: undefined,
          latitude: undefined,
          longitude: undefined,
          shopUrl: undefined
        }
      },
      handleCreate() {
        //this.getAdmin()
        this.resetForm()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      /*
      getAdmin() {
        listAdmin()
          .then(response => {
            this.listAdmin = response.data.data.list
          })
      },*/
      uploadUrl: function(response) {
        this.dataForm.shopUrl = response.data.url
      },
      checkFileSize: function(file) {
        if (file.size > 2097152) { //2M 2097152
          this.$message.error(`${file.name}文件大于1024KB，请选择小于1024KB大小的图片`)
          return false
        }
        return true
      },
      createShopSettingData() {
        this.$refs['dataFormSetting'].validate(valid => {
          if (valid) {
            createShopSetting(this.dataFormSetting)
              .then(response => {
                this.dialogFormSetting = false
                this.$notify.success({
                  title: '成功',
                  message: '设置成功'
                })
              })
              .catch(response => {
                this.$notify.error({
                  title: '失败',
                  message: response.data.errmsg
                })
              })
          }
        })
      },
      updateShopSettingData() {
        this.$refs['dataFormSetting'].validate(valid => {
          if (valid) {
            updateShopSetting(this.dataFormSetting)
              .then(() => {
                this.dialogFormSetting = false
                this.$notify.success({
                  title: '成功',
                  message: '更新设置成功'
                })
              })
              .catch(response => {
                this.$notify.error({
                  title: '失败',
                  message: response.data.errmsg
                })
              })
          }
        })
      },
      createData() {
        this.$refs['dataForm'].validate(valid => {
          if (valid) {
            createShop(this.dataForm)
              .then(response => {
                this.list.unshift(response.data.data)
                this.dialogFormVisible = false
                this.$notify.success({
                  title: '成功',
                  message: '创建成功'
                })
              })
              .catch(response => {
                this.$notify.error({
                  title: '失败',
                  message: response.data.errmsg
                })
              })
          }
        })
      },
      handleUpdate(row) {
        //this.getAdmin()
        this.dataForm = Object.assign({}, row)
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      handleUpdate2(row) {
        //this.getAdmin()
        this.dataForm = Object.assign({}, row)
        this.dialogStatus = 'update'
        this.dialogFormBound = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      handleCreateSetting(row) {
        //this.dataFormSetting = Object.assign({}, row)
        this.dataFormSetting = {}
        this.dataFormSetting.shopId = row.id
        this.dialogStatus = 'setting'
        this.dialogFormSetting = true
        this.selectShopSetting(row.id)
        /*
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })*/
      },
      selectShopSetting(ShopId) {
        getOneSetting(ShopId)
          .then(response => {
            if(response.data.data){
              //说明有数据
              this.dialogStatus = 'updateSetting'
              this.dataFormSetting = response.data.data
              this.elRadioStatus = response.data.data.deliveryStatus+'';
            }
          })
      },

      updateData() {
        this.$refs['dataForm'].validate(valid => {
          if (valid) {
            updateShop(this.dataForm)
              .then(() => {
                for (const v of this.list) {
                  if (v.id === this.dataForm.id) {
                    const index = this.list.indexOf(v)
                    this.list.splice(index, 1, this.dataForm)
                    break
                  }
                }
                this.dialogFormVisible = false
                this.$notify.success({
                  title: '成功',
                  message: '更新门店成功'
                })
              })
              .catch(response => {
                this.$notify.error({
                  title: '失败',
                  message: response.data.errmsg
                })
              })
          }
        })
      },
      updateBoundData() {
        this.$refs['dataForm'].validate(valid => {
          if (valid) {
            updateShopBound(this.dataForm)
              .then(() => {
                for (const v of this.list) {
                  if (v.id === this.dataForm.id) {
                    const index = this.list.indexOf(v)
                    this.list.splice(index, 1, this.dataForm)
                    break
                  }
                }
                this.dialogFormBound = false
                this.$notify.success({
                  title: '成功',
                  message: '绑定成功'
                })
              })
              .catch(response => {
                this.$notify.error({
                  title: '失败',
                  message: response.data.errmsg
                })
              })
          }
        })
      },
      updateShopOff() {
            updateShopOff(this.dataForm)
              .then(() => {
                /*
                for (const v of this.list) {
                  if (v.id === this.dataForm.id) {
                    const index = this.list.indexOf(v)
                    this.list.splice(index, 1, this.dataForm)
                    break
                  }
                }*/
                //this.dialogFormVisible = false
                this.$notify.success({
                  title: '成功',
                  message: '更新门店状态成功'
                })
              })
              .catch(response => {
                /*
                this.$notify.error({
                  title: '失败',
                  message: response.data.errmsg
                })*/
                  this.$alert(response.data.errmsg, '失败', {
                    confirmButtonText: '确定',
                    callback: action => {
                      /*
                      this.$message({
                        type: 'info',
                        message: `action: ${ action }`
                      });*/
                    }
                  });
                this.dataForm.shopOff = 1
              })
      },

      handleDelete(row) {
        deleteShop(row)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '删除成功'
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.errmsg
            })
          })
      },
      handleDownload() {
        this.downloadLoading = true
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = [
            '广告ID',
            '广告标题',
            '广告内容',
            '广告图片',
            '广告位置',
            '活动链接',
            '是否启用'
          ]
          const filterVal = [
            'id',
            'name',
            'content',
            'url',
            'postion',
            'link',
            'enabled'
          ]
          excel.export_json_to_excel2(tHeader, this.list, filterVal, '广告信息')
          this.downloadLoading = false
        })
      }
    }
  }
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #20a0ff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
  }

  .avatar {
    width: 145px;
    height: 145px;
    display: block;
  }
</style>
